onload = () => {
    loadCSS("../css/fontello.css", "bootstrap5-icon");
    loadCSS("../css/bootstrap5.min.css", "bootstrap5");
    loadCSS("../css/common.css", "common");
    loadScript("../js/bootstrap5.bundle.min.js")
        .then(() => loadScript("../js/crud.js")).then(() => {
        let apOperator = new Crud({
            module: "apDetail",
            hasCheckbox: true,
            iterators: [{
                name: "ap.carrier", type: "apCarrier", convert: u => {
                    return {value: u, "caption": u}
                }
            }],
            extendAttribute: [{name: "apDetailId", type: "apCharge"},
                {name: "trackingNo", type: "arChargeByTrackingNo"},
                {name: "updatedBy", type: "userById"}],
            opsButton: ["delete", {
                "caption": "Delete By BillNo",
                "class": "btn btn-primary",
                "callback": () => {
                    let billNo = prompt("Please input bill# to be deleted.");
                    if (billNo)
                        return ajax("/ap/deleteByBill?billNo=" + billNo, {method: "GET"}, data => {
                            showToast(`Delete successful: ${JSON.stringify(data.data)}`, "primary");
                            loadData();
                        }, error => showToast(`ERROR: description: ${error}`));
                }
            }, {
                "caption": "Upload AP By carrier",
                "class": "btn btn-primary",
                hint: "Add AP file",
                "action": "modal",
                "param": "#uploadQuoteFile",
                "commit": (form, e) => {
                    const fileInput = form.querySelector('#formFile');
                    const formData = new FormData();
                    formData.append('file', fileInput.files[0]);
                    formData.append("carrier", form.querySelector("#carrier").value);
                    return ajax("/ap/excel", {method: "POST", body: formData, headers: {}}, data => {
                        showToast(`Upload successful: ${JSON.stringify(data.data)}`, "primary");
                        loadData();
                        let modalElement = document.getElementById("uploadQuoteFile");
                        const modal = bootstrap.Modal.getInstance(modalElement)
                            || new bootstrap.Modal(modalElement);
                        modal.hide();
                    }, error => {
                        showToast(`ERROR: description: ${error}`)
                    });
                }
            }, {
                "caption": "Upload AP By Template/CSV",
                "class": "btn btn-primary",
                hint: "Add AP file",
                "action": "modal",
                "param": "#uploadAp",
                "commit": (form, e) => {
                    const fileInput = form.querySelector('#templateFile');
                    const formData = new FormData();
                    formData.append('file', fileInput.files[0]);
                    formData.append("template", form.querySelector("#carrierTemplate").value);
                    const url = (fileInput.files[0].name.endsWith(".xlsx")) ? "/ap/template" : "/ap/csv";
                    return ajax(url, {method: "POST", body: formData, headers: {}}, data => {
                        showToast(`Upload successful: ${JSON.stringify(data.data)}`, "primary");
                        loadData();
                        let modalElement = document.getElementById("templateFile");
                        const modal = bootstrap.Modal.getInstance(modalElement)
                            || new bootstrap.Modal(modalElement);
                        modal.hide();
                    }, error => {
                        showToast(`ERROR: description: ${error}`)
                    });
                }
            }, {
                caption: "Toggle To Exception",
                class: "btn btn-warning",
                callback: (a, b, c, d) => {
                    exception(a);
                }
            }, "export"],
            rowBtn: ["delete"],
            search: [
                {"caption": "Bill #", "type": "text", "name": "billNo", class: "col-3"},
                {"caption": "Tracking #", "type": "text", "name": "trackingNo", class: "col-3"},
                {"caption": "Carrier", "type": "combo", "name": "carrier", iterator: "blank_ALL_ap.carrier", class: "col-3"},
                {"caption": "From", "type": "date", "name": "fromDate", class: "col-3"},
                {"caption": "To", "type": "date", "name": "toDate", class: "col-3"},
            ],
            listField: [{"caption": "ID", "field": "apDetailId"},
                {caption: "Tracking#", "field": "trackingNo"},
                {caption: "Carrier", "field": "carrier"},
                {
                    caption: "Bill Time",
                    "field": "billingTime",
                    format: str => subString(str, 0, 10)
                },
                {caption: "Create Time", "field": "initTime", format: str => subString(str, 0, 10)},
                {caption: "Biz. Time", "field": "bizTime", format: str => subString(str, 0, 10)},
                {caption: "Fee", "field": "fee", format: v => v / 100},
                {
                    caption: "Profit", "field": item => profit(item), format: (str, td) => {
                        td.classList.add(str === "No AR" ? "text-danger" : Number(str) > 0 ? "text-primary" : "text-warning");
                        return str;
                    }
                },
                {caption: "Currency", "field": "currency"},
                {caption: "Weight(LB)", "field": "weight", format: str => (str / 454).toFixed(2)},
                {
                    caption: "Dimension(INCH)",
                    "field": item => (item.length / 254).toFixed(1) + " * " + (item.width / 254).toFixed(1) + " * " + (item.height / 254).toFixed(1)
                },
                {caption: "UpdateTime", "field": "createTime", format: str => subString(str, 0, 10)},
                {caption: "UpdatedBy", "field": "updatedBy_userById.userName"}],
            rowEvent: function (e, item, tr, outer) {
                outer.subTable["chargeTable"].load(item["apDetailId_apCharge"]);
                outer.subTable["chargeTable2"].load(item["trackingNo_arChargeByTrackingNo"]);
                canvas.show();
            },
            subTable: [{
                name: "chargeTable",
                tableId: "chargeTable",
                stat: stat,
                listField: [{"caption": "Bill#", "field": "billNo"},
                    {"caption": "Bill Time", "field": "billingTime", format: str => subString(str, 0, 10)},
                    {"caption": "Charge Code", "field": "chargeCode"},
                    {"caption": "Fee", "field": "fee", format: str => str / 100},
                    {"caption": "Currency", "field": "currency"},
                ]
            }, {
                name: "chargeTable2",
                tableId: "chargeTable2",
                stat: stat,
                listField: [{"caption": "Bill#", "field": "billNo"},
                    {"caption": "Charge Code", "field": "chargeCode"},
                    {"caption": "Bill Time", "field": "billingTime", format: str => subString(str, 0, 10)},
                    {"caption": "Fee", "field": "fee", format: str => str / 100},
                    {"caption": "Currency", "field": "currency"},
                    {"caption": "AR ID", "field": "arStatementId"},
                    {"caption": "AP ID", "field": "apStatementId"}
                ]
            }],
            editFields: [
                {"name": "code", "placeHolder": "code", "required": "required"},
                {"name": "pk", "placeHolder": "PK in cargo wise", "required": "required"},
                {caption: "Full Name:", "name": "fullname", "placeHolder": "Full name", "required": "required"}
            ]
        });
        apOperator.init();
        apOperator.setCrudLink("export", "/bill_info/ap/export");
        function exception(event) {
            if (event.target.innerText !== "Toggle To List") {
                event.target.innerText = "Toggle To List";
                apOperator.setCrudLink("list", "/ap/exception");
                apOperator.setCrudLink("export", "/bill_info/ap/exception/export");
            } else {
                event.target.innerText = "Toggle To Exception";
                apOperator.setCrudLink("list", "/ap_detail/list");
                apOperator.setCrudLink("export", "/bill_info/ap/export");
            }
            loadData();
        }
        function loadData() {
            apOperator.loadData();
        }
        function setCrudLink(a, b) {
            apOperator.setCrudLink(a, b);
        }
        function stat() {
            const arTable = document.getElementById("chargeTable2");
            const apTable = document.getElementById("chargeTable");
            let rows = arTable.querySelector("tbody").querySelectorAll("tr");
            let revenue = 0;
            rows.forEach(row => {
                revenue += Number(row.querySelectorAll("td")[3]?.innerText)
            });
            rows = apTable.querySelector("tbody").querySelectorAll("tr");
            let cost = 0;
            rows.forEach(row => {
                cost += Number(row.querySelectorAll("td")[3]?.innerText)
            });
            document.getElementById("stat_revenue").innerHTML = revenue.toFixed(2);
            document.getElementById("stat_cost").innerHTML = cost.toFixed(2);
            document.getElementById("stat_profit").innerHTML = (revenue - cost).toFixed(2);
            if (revenue > cost) {
                document.getElementById("stat_profit").classList.remove("text-danger");
                document.getElementById("stat_profit").classList.add("text-primary");
            } else {
                document.getElementById("stat_profit").classList.remove("text-primary");
                document.getElementById("stat_profit").classList.add("text-danger");
            }
            document.getElementById("stat_margin").innerHTML = (100 * (revenue - cost) / revenue).toFixed(2);
        }
        ajax("/common/mapper?type=carrierApTemplate", {"Method": "GET"}).then(data => data.data).then(data => {
            const selectElement = document.getElementById("carrierTemplate");
            data.forEach(row => {
                let option = document.createElement("option");
                option.value = row.name;
                option.textContent = row.name;
                selectElement.appendChild(option);
            })
        });
        function profit(item) {
            if (!item.trackingNo_arChargeByTrackingNo || item.trackingNo_arChargeByTrackingNo.length == 0)
                return "No AR";
            else {
                const cost = item.apDetailId_apCharge.map(i => i.fee).reduce((a, b) => a + b, 0);
                const revenue = item.trackingNo_arChargeByTrackingNo.map(i => i.fee).reduce((a, b) => a + b, 0);
                return ((revenue - cost) / 100).toFixed(2);
            }
        }
        const canvas = new bootstrap.Offcanvas(document.getElementById('subtable'));
    }).catch((err) => console.error(err));
}
